import nibabel as nib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from scipy.ndimage import zoom

# 读取NIfTI文件
ti_img = nib.load('C:/Users/Administrator/Desktop/研究生的幸福生活/项目/医学可视化/甲方提供的资料/MNI152_T1_1mm.nii.gz')
#target_img = nib.load('C:/Users/Administrator/Desktop/研究生的幸福生活/项目/医学可视化/甲方提供的资料/ID03_MOTOR_ICA.nii.gz')
target_img = nib.load('combined_image.nii')
#target_img = nib.load('C:/Users/Administrator/Desktop/研究生的幸福生活/项目/医学可视化/甲方提供的资料/ID03_MOTOR_ICA.nii.gz')
# 获取图像数据
ti_data = ti_img.get_fdata()
target_data = target_img.get_fdata()
print(ti_data)
print(target_data)
#仿射矩阵的信息
t1_affine = ti_img.affine
target_affine = target_img.affine
print(t1_affine)
print(target_affine)

# 先确定目标图像的形状
ti_shape = ti_data.shape
target_shape = target_data.shape

#将体素坐标转换为世界坐标
x_indices, y_indices, z_indices = np.indices(ti_shape)
voxel_coords = np.array([x_indices.flatten(), y_indices.flatten(), z_indices.flatten()]).T
voxel_coords_homogeneous = np.hstack([voxel_coords, np.ones((voxel_coords.shape[0], 1))])
world_coords = t1_affine.dot(voxel_coords_homogeneous.T).T[:, :3]

x_indices1, y_indices1, z_indices1 = np.indices(target_shape)
voxel_coords1 = np.array([x_indices1.flatten(), y_indices1.flatten(), z_indices1.flatten()]).T
voxel_coords_homogeneous1 = np.hstack([voxel_coords1, np.ones((voxel_coords1.shape[0], 1))])
world_coords1 = target_affine.dot(voxel_coords_homogeneous1.T).T[:, :3]

print("我在这")
print(world_coords.shape)
print(world_coords1.shape)

print(ti_shape)
print(target_shape)
print("image",target_img)

# 计算缩放因子
zoom_factors = np.array(ti_shape) / np.array(target_shape)
print("缩放因子：",zoom_factors)
# 重采样目标图像
target_data_resampled = zoom(target_data, zoom_factors, order=1)  # 使用线性插值

# 确保两者数据形状相同
if ti_data.shape != target_data_resampled.shape:
    raise ValueError("两个NIfTI图像的形状不一致，请检查.")

# 图像维度
x_dim, y_dim, z_dim = ti_data.shape

# 创建图形和子图
fig, axs = plt.subplots(1, 3, figsize=(15, 5))

# 设置滑块位置
ax_slider_x = plt.axes([0.2, 0.01, 0.6, 0.03])  # X轴滑块
ax_slider_y = plt.axes([0.2, 0.05, 0.6, 0.03])  # Y轴滑块
ax_slider_z = plt.axes([0.2, 0.09, 0.6, 0.03])  # Z轴滑块

# 创建滑块
slider_x = Slider(ax_slider_x, 'X', 0, x_dim - 1, valinit=x_dim // 2, valstep=1)
slider_y = Slider(ax_slider_y, 'Y', 0, y_dim - 1, valinit=y_dim // 2, valstep=1)
slider_z = Slider(ax_slider_z, 'Z', 0, z_dim - 1, valinit=z_dim // 2, valstep=1)


# 用于更新显示函数
def update_images(val):
    x_idx = int(slider_x.val)
    y_idx = int(slider_y.val)
    z_idx = int(slider_z.val)

    # 清空子图，然后重绘
    for ax in axs:
        ax.clear()

    # 提取三个切片
    ti_slice_x = ti_data[x_idx, :, :]
    target_slice_x = target_data_resampled[x_idx, :, :]

    ti_slice_y = ti_data[:, y_idx, :]
    target_slice_y = target_data_resampled[:, y_idx, :]

    ti_slice_z = ti_data[:, :, z_idx]
    target_slice_z = target_data_resampled[:, :, z_idx]

    # 绘制剖面
    #axs[0].imshow(ti_slice_x, cmap='gray', alpha=0.5)
    axs[0].imshow(target_slice_x, cmap='jet', alpha=0.5)
    axs[0].set_title(f'X Slice: {x_idx}')

    #axs[1].imshow(ti_slice_y.T, cmap='gray', alpha=0.5)
    axs[1].imshow(target_slice_y.T, cmap='jet', alpha=0.5)
    axs[1].set_title(f'Y Slice: {y_idx}')

    #axs[2].imshow(ti_slice_z.T, cmap='gray', alpha=0.5)
    axs[2].imshow(target_slice_z.T, cmap='jet', alpha=0.5)
    axs[2].set_title(f'Z Slice: {z_idx}')

    # 更新图像
    for ax in axs:
        ax.axis('off')

    plt.draw()


# 连接滑块与更新函数
slider_x.on_changed(update_images)
slider_y.on_changed(update_images)
slider_z.on_changed(update_images)

# 初次绘制
update_images(None)

#plt.tight_layout()
plt.show()